package com.seguriapp.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.seguriapp.common.security.SeguriAppSession;
import com.seguriapp.common.security.SeguriAppSession.Key;
import com.seguriapp.common.security.SeguriAppUser;
import com.seguriapp.entities.User;

/**
 * Represents the controller for the alerts entities
 * 
 * @author Tania Gonzales(taniadgv@gmail.com)
 */
@Controller
@RequestMapping("/resources")
public class ResourceController {

  private static final Logger LOGGER = Logger.getLogger(ResourceController.class);

  private static final String IMAGES_DIR = "images/";
  private static final String VIDEOS_DIR = "videos/";
  private static final String AUDIOS_DIR = "audios/";

  @RequestMapping("/image/{imageName}")
  public String getImageResource(final HttpServletRequest request, @PathVariable String imageName) {
    return getResourceRedirectUrl(request, imageName, IMAGES_DIR);
  }

  @RequestMapping("/video/{videoName}")
  public String getVideoResource(final HttpServletRequest request, @PathVariable String videoName) {
    return getResourceRedirectUrl(request, videoName, VIDEOS_DIR);
  }

  @RequestMapping("/audio/{audioName}")
  public String getAudioResource(final HttpServletRequest request, @PathVariable String audioName) {
    return getResourceRedirectUrl(request, audioName, AUDIOS_DIR);
  }

  private String getResourceRedirectUrl(final HttpServletRequest request, final String resourceName, final String dirName) {
    SeguriAppSession session = SeguriAppUser.getSeguriAppSecureUser().getSeguriAppSession();
    final User user = (User) session.get(Key.User);
    final String redirectUrl = request.getRequestURL().toString()
        .substring(0, request.getRequestURL().toString().indexOf(request.getContextPath()) + 1);
    if (user != null) {
      final String fileName = new String(Base64.decodeBase64(resourceName.getBytes()));
      LOGGER.info("Required resource: " + fileName + " by user: " + user.getUsername());
      return "redirect:" + redirectUrl + "resources/" + dirName + fileName;
    } else {
      //return "redirect:" + request.getRequestURL().toString() + "error/accessDenied";
      return "accessDenied";
    }
  }

}
